#!/usr/bin/Rscript
##########################################################################################
# Social Media and Policy Responses to the COVID-19 Pandemic in Switzerland
##########################################################################################
# Description:
##########################################################################################
# Appendix Figure 1
##########################################################################################
# Contents
##########################################################################################
# 1) Dependencies
# 2) Data Import
# 3) Data Processing
# 5) Figre A4 (Lag Structure)
##########################################################################################
# 1) Dependencies
##########################################################################################
library(dplyr)
library(ggplot2)
library(stringr)
library(forcats)
library(showtext)
library(stringr)
library(forcats)
##########################################################################################
# 2) Data Import
##########################################################################################
rm(list=ls())
# - set dir
args = commandArgs()

scriptName = args[substr(args,1,7) == '--file=']

if (length(scriptName) == 0) {
  scriptName <- rstudioapi::getSourceEditorContext()$path
} else {
  scriptName <- substr(scriptName, 8, nchar(scriptName))
}

pathName = substr(
  scriptName, 
  1, 
  nchar(scriptName) - nchar(strsplit(scriptName, '.*[/|\\]')[[1]][2])
)

setwd(pathName)
parent_path <- getwd()

# - load fonts used in plots
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")

# - define a global seed (used in all scripts)
set.seed(2019)

# - load irf data 
final_input <- readRDS("../var/onetime-structural-shock-irfs-results_all_small_de_only_no_fb.RDS")

# - topic names for model selection
mod_name_nice <- c("Covid19", "Masks", "App", "All Three")

# - load ddl theme
suppressMessages(suppressWarnings(source('ggplot_theme_ddl.R')))
##########################################################################################
# 3) Data Processing
##########################################################################################
#-----------------------------------------------------------------------------------------
# - get data for responsiveness plot of all topics together
all_opics_all <- final_input[[4]]
all_opics_all$topic <- mod_name_nice[4]
all_opics_all <- all_opics_all %>% dplyr::filter(day %in% c(1,2,3,4,5,6,7,8,9))
all_opics_all <- all_opics_all %>% dplyr::filter(out %in% c("Media_SMD", "Politican_TW", "Party_TW", "SnowBallers_TW")) %>%
  dplyr::filter(cov %in% c("Media_SMD", "Politican_TW", "Party_TW", "SnowBallers_TW")) 

# - relabel the outcomes so they fit/look better in the plot
all_opics_all$out <- recode(as.character(all_opics_all$out),
                            `Media_SMD` = "Newspaper Articles",
                            `Politican_TW` = "Tweets by Politicians",
                            `Party_TW` = "Tweets by Parties",
                            `SnowBallers_TW` = "Tweets by informed Public")

# - relabel the covariates so they fit/look better in the plot
all_opics_all$cov <- recode(as.character(all_opics_all$cov),
                            `Media_TW` = "Newspapers on Twitter",
                            `Politican_TW` = "Tweets by Politicians",
                            `Party_TW` = "Tweets by Parties",
                            `SnowBallers_TW` = "Tweets by informed Public")

plot_resp_i <- all_opics_all %>%
  filter(day == 7 & data_type == "Effect of a one time 10 percentage point attention increase at day 0") %>%
  mutate(cov2 = cov) %>%
  mutate(out2 = out) %>%
  mutate(direction = paste0(cov2, " -> ", out2))

#-----------------------------------------------------------------------------------------
# - combine data from all four topics models
for(n in 1:(length(final_input)-1)){
  tmp <- final_input[[n]]
  tmp$topic <- mod_name_nice[n]
  
  if(n == 1){
    all_topics <- tmp
  } else if(n == 3){
    all_topics <- rbind(all_topics, tmp)
    all_topics <- all_topics %>% dplyr::filter(day %in% c(1,2,3,4,5,6,7,8,9))
    all_topics <- all_topics %>% dplyr::filter(out %in% c("Media_SMD", "Politican_TW", "Party_TW", "SnowBallers_TW")) %>% #"Media_FB", "Media_TW",  "Politcan_FB", "Party_FB"
      dplyr::filter(cov %in% c("Media_SMD", "Politican_TW", "Party_TW", "SnowBallers_TW")) #"Media_FB", "Media_TW", "Politican_FB", "Party_FB"
    # - relabel the outcomes so they fit/look better in the plot
    all_topics$out <- recode(as.character(all_topics$out),
                             Media_SMD = "Newspaper Articles",
                             Politican_TW = "Tweets by Politicians",
                             Party_TW = "Tweets by Parties",
                             SnowBallers_TW = "Attentive Public")
    
    # - relabel the covariates so they fit/look better in the plot
    all_topics$cov <- recode(as.character(all_topics$cov),
                             Media_SMD = "Newspaper Articles",
                             Politican_TW = "Tweets by Politicians",
                             Party_TW = "Tweets by Parties",
                             SnowBallers_TW = "Attentive Public")
    
  } else {
    all_topics <- rbind(all_topics, tmp)
    rm(tmp)
  }
}

all_topics$out <- recode(as.character(all_topics$out),
                         Media_SMD = "Newspaper Articles",
                         Politican_TW = "Tweets by Politicians",
                         Party_TW = "Tweets by Parties",
                         SnowBallers_TW = "Attentive Public")

# - relabel the covariates so they fit/look better in the plot
all_topics$cov <- recode(as.character(all_topics$cov),
                         Media_SMD = "Newspaper Articles",
                         Politican_TW = "Tweets by Politicians",
                         Party_TW = "Tweets by Parties",
                         SnowBallers_TW = "Attentive Public")

# - rename values for nicer plot of responsiveness plot per topic
plot_resp_ii <- all_topics %>%
  filter(day == 7 & data_type == "Effect of a one time 10 percentage point attention increase at day 0") %>%
  mutate(cov2 = cov) %>%
  mutate(out2 = out) %>%
  mutate(direction = paste0(cov2, " -> ", out2)) %>%
  mutate(TOPIC = str_to_upper(topic)) %>%
  mutate(topic = fct_relevel(topic, "Covid19", "Masks", "App")) %>%
  mutate(topic_rev = fct_relevel(topic, "App", "Masks", "Covid19"))
##########################################################################################
# 5) Figre A4 (Lag Structure)
##########################################################################################
plot_resp_ii <- all_topics %>%
  filter(day %in% c(1,3,5,7) & data_type == "Effect of a one time 10 percentage point attention increase at day 0") %>%
  mutate(cov2 = cov) %>%
  mutate(out2 = out) %>%
  mutate(direction = paste0(cov2, " -> ", out2)) %>%
  mutate(TOPIC = str_to_upper(topic)) %>%
  mutate(topic = fct_relevel(topic, "Covid19", "Masks", "App")) %>%
  mutate(topic_rev = fct_relevel(topic, "App", "Masks", "Covid19"))

facet_names <- c(`Tweets by Parties` = "of Tweets by Parties with on:",
                 `Tweets by Politicians` = "of Tweets by Politicians on:",
                 `Newspaper Articles` = "of Newspaper Articles on:",
                 `Attentive Public` = "of Tweets by Attentive Public on:")

facet_names_2 <- c(`1` = "Cummulated Effect after 1 Day",
                   `3` = "Cummulated Effect after 3 Days",
                   `5` = "Cummulated Effect after 5 Days",
                   `7` = "Cummulated Effect after 7 Days")

max_width <- max(nchar(as.character(plot_resp_ii$out)))
plot_resp_ii$out <- sprintf(paste0("%-",max_width, "s"), plot_resp_ii$out)

ggplot(data = plot_resp_ii) +
  aes(x = out, y = pe, ymin = lwr, ymax = upr, group = topic_rev, color = topic, shape = topic) +
  geom_linerange(size = 2.5, position = position_dodge(width = 0.55), alpha = 0.4) +  
  geom_point(position = position_dodge(width = 0.55), size = 2.5) +
  geom_hline(aes(yintercept = 0), color = "black", linetype = 2, alpha = 0.75) +
  coord_flip() +
  labs (subtitle = "", #(Effect of a one-time 10-percentage-point-increase over next 7 days)
        title = "", #Attention responsiveness of parties, candidates, and newspapers 
        y = "Percentage points", x = "") +
  facet_wrap(day ~ cov,  ncol = 2, nrow = 8, scales = "free_y", labeller = labeller(cov = as_labeller(facet_names), day =  as_labeller(facet_names_2))) + 
  scale_y_continuous(breaks = c(-2,-1,0,1,2,3,4)) +
  scale_color_manual(labels = c("Covid19","Masks","App"), values = c("#DD2461", "#0072B2", "#999999")) +
  scale_fill_manual(labels = c("Covid19","Masks","App"), values = c("#DD2461", "#0072B2", "#999999")) +
  ddl_theme(panel.grid.major = element_blank(),
            panel.grid.minor = element_blank()) +
  theme(legend.position = "bottom", legend.title = element_blank(), 
        strip.background = element_blank(), strip.text = element_text(color = "black"),
        axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.0, size = 16, color = "black"),  
        axis.text.y = element_text(hjust=0, size = 16, color = "black"),
        axis.ticks.y = element_blank(),
        axis.title = element_text(size = 16, color = "black"),
        strip.text.x = element_text(size = 16, color = "black"),
        legend.text = element_text(size = 16, color = "black"),
        plot.title = element_blank(),
        plot.margin = unit(c(.5,.5,.5,.5), "cm"),
        legend.key.size = unit(1.5,"line"),
        legend.key = element_blank(),
        axis.line.x = element_line(color="black", size = .5),
        axis.line.y = element_line(color="black", size = .5),
        panel.spacing.y = unit(2.5, "lines"),
        panel.spacing.x = unit(.8, "lines")) +
  guides(color = guide_legend(override.aes = list(size=2)))

ggsave("../images/figure_A4.pdf", width = 12.5, height = 17.62, device = cairo_pdf)